/**
 * 注册校验
 * @authors supmain (mtingfeng@gmail.com)
 * @date    2014-09-05 11:10:42
 * @update  2014-09-05 11:10:42
 * @for register.jsp
 * @version $Id$
 */
var BSTYUN = BSTYUN || {};
BSTYUN.check = {
    //IE6判定
    isIE6: window.VBArray && !window.XMLHttpRequest,
    //判断是否为中英文，数字，下划线，减号
    isNick: function(str) {
        var nickReg = /^[\u4e00-\u9fa5A-Za-z0-9-_]+$/;
        return nickReg.test(str);
    },
//    //判断邮箱
//    isEmail: function(str) {
//        var emailReg = /^[a-z0-9][\w\.]*@([a-z0-9][a-z0-9-]*\.)+[a-z]{2,5}$/i;
//        return emailReg.test(str);
//    },
    //判断手机.
    isMobile: function(str) {
        var mobileReg = /^1[345678][0-9]{9}$/;
        return mobileReg.test(str);
    },
    // 判断固话
    isTelephone: function(str) {
        var phoneReg = /^0\d{2,3}-\d{5,9}$/;
        return phoneReg.test(str);
    },
    //判断URL
    isUrl: function(str) {
        var urlReg = /^http:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?$/;
        return urlReg.test(str);
    },
    //判断数字
    isNum: function(str) {
        var numReg = /^[0-9]\d*$/;
        return numReg.test(str);
    }
};
BSTYUN.register = {
    $inputs: null,
    flag: {email: false, psd: false, cfm_psd: false, phone: false, vftn_code: false, picode: false},
    _timer: null,/*全局定时器*/
    init:function() {
        var that = this;
        /*获取input元素*/
        that.$inputs = $('.input_box').find('input');
        /*检测信息*/
        that.checkInfor();
        /*发送短信验证码*/
        that.sendSmsCode();
        /*提交注册*/
        that.submitRegister();
        /*图片验证码替换*/
        that.changePicCode();
    },
    checkInfor:function() {
        var that = this;
        /*获取焦点，清空错误信息*/
        that.$inputs.on('focus', function(event) {
            that.clearErrorMsg($(this));
            /*失去焦点，检测信息正确性*/
        }).on('blur', function(event) {
            var $this = $(this),
                typename = $this.attr('name'),
                val = $.trim($this.val());
            /*输入内容为空，则提示不能为空*/
            if(val == '' || val.length == 0){
                that.addErrorMsg($this,'不能为空');
                return false;
            }
            if (typename == 'phone') {
            	var $send = $('#getvftn_code');
                if (!BSTYUN.check.isMobile(val)) {
                    that.addErrorMsg($this,'手机号码格式不正确');
                }else{
                	$.ajax({
                        type: "post",
                        url: "/user/tel?random="+Math.random(),
                        data: {userTel:val},
                        async:false,
                        success: function(data){
                          if(data==false){
                              that.addErrorMsg($this,"该手机号码已被注册");
                              $send.addClass("disabled");
                          }else{
                        	  that.clearErrorMsg($this);
                        	  $send.removeClass("disabled");
                          }
                       }
                    });
                }
            }else if (typename == 'psd') {
                var $cfm_psd = $this.parents('.input_box').next().find('#cfm_psd'),
                    cfm_psd_val = $.trim($cfm_psd.val());
                if (val.length<6 || val.length >20) {
                    that.addErrorMsg($this,'长度必须在6-20之间');
                }
                if (cfm_psd_val != '' || cfm_psd_val.length != 0) {
                    if (val != cfm_psd_val) {
                        that.addErrorMsg($cfm_psd,'两次输入密码不一致');
                    }else{
                        that.clearErrorMsg($cfm_psd);
                    };
                };
            }else if (typename == 'cfm_psd') {
                var psd = $.trim($this.parents('.input_box').prev().find('#psd').val());
                if (val != psd) {
                    that.addErrorMsg($this,'两次输入密码不一致');
                };
            }else if (typename == 'vftn_code') {
                
            }else if (typename == 'picode') {
                
            };
        });
        /*判断手机号，是否可以发送短信验证码*/
        that.$inputs.filter("[name='phone']").on('keyup', function(event) {
            var $send = $('#getvftn_code'),
            	$this = $(this),
                val = $.trim($this.val());
            //if(BSTYUN.register._timer != null){return false;};
            if (!BSTYUN.check.isMobile(val)) {
                $send.addClass('disabled');
            }else{
            	/*存在倒计时，清空倒计时*/
                if(that._timer != null){
                	$("#getvftn_code").removeClass('disabled').text('获取免费短信验证码');
                	clearInterval(that._timer);
                }
                $send.removeClass('disabled');
                /*判断手机号，是否已经被注册*/
                $.ajax({
                    type: "post",
                    url: "/user/tel?random="+Math.random(),
                    data: {userTel:val},
                    async:false,
                    success: function(data){
                      if(data==false){
                          that.addErrorMsg($this,"该手机号码已被注册");
                          $send.addClass("disabled");
                      }else{
                    	  that.clearErrorMsg($this);
                    	  $send.removeClass("disabled");
                      }
                   }
                });
            }
        });
    },
    sendSmsCode: function(argument) {
        var that = this,
            $send = $('#getvftn_code'),
            $phone = that.$inputs.eq(0),
            val = null;
            $send.on('click', function(event) {
                var $this = $(this);
                if (!$this.hasClass('disabled')) {
                    $this.addClass('disabled');
                    val = $.trim($phone.val());
                    /*发送ajax请求短信验证码*/
                    $.ajax({
                        type: "post",
                        url: "/user/getMsgCode?random="+Math.random(),
                        //url: "text.txt?random="+Math.random(),
                        data: {tel:val},
                        success: function(data){
                            var message = data.message;
                            if(message=="发送失败"){
                                that.addErrorMsg($phone,'短信发送失败，请重试！');
                                $this.removeClass('disabled').text('获取免费短信验证码');
                                return false;
                            }else if(message=="每天最多只能发送三次"){
                                that.addErrorMsg($phone,'每天最多只能发送三次');
                                $this.removeClass('disabled').text('获取免费短信验证码');
                                return false;
                            }else{
                                that.addTipMsg($phone,'短信发送成功');
                                /*倒计时重发*/
                                var i = 60;
                                clearInterval(that._timer);
                                that._timer = setInterval(function() {
                                    if (i == 0) {
                                        clearInterval(that._timer);
                                        that._timer = null;
                                        $this.removeClass('disabled').text('获取免费短信验证码');
                                    } else {
                                        i--;
                                        $this.text('再次发送验证码(' + i + ')');
                                    }
                                }, 1000);
                            }
                        }
                    });
                }else{
                   /*禁止状态，不能点击*/
                   return false;
                };
            });
    },
    submitRegister:function() {
        var that = this,
            $submit = $("#go2register");
        $submit.on('click', function(event) {
            var flag = that.flag,
                data = {};
            $.each(that.$inputs, function(index, val) {
                 $(this).trigger('blur');
            });
            if (flag.phone != false&&flag.psd != false && flag.cfm_psd != false && flag.vftn_code != false && flag.picode != false ) {
            	data.phone = $.trim(that.$inputs.eq(0).val()),
            	data.vftn_code = $.trim(that.$inputs.eq(1).val()),
                data.psd = $.trim(that.$inputs.eq(2).val()),
                data.cfm_psd = $.trim(that.$inputs.eq(3).val()),
                data.picode = $.trim(that.$inputs.eq(4).val());
                $.ajax({
                    type: "POST",
                    url : "/user?random="+Math.random(),
                    data: data,
                    async: false,
                    error: function(request) {
                    	BSTYUN.dialog.ok('服务器繁忙，请稍后尝试')
                        return false;
                    },
                    success: function(data) {
                        var messageCode = data.messageCode;
                        var imgSuccess = data.imgSuccess;
                        var saveSuccess = data.saveSuccess;
                        if(messageCode==true){
                            if(imgSuccess==false&&saveSuccess==""){
                                that.addErrorMsg(that.$inputs.filter("[name='picode']"),'验证码错误');
                                return false;
                            }else{
                                if (saveSuccess == true) {
                                    window.location.href = "/user/userCenter"
                                }
                            }
                        }else{
                            that.addErrorMsg(that.$inputs.filter("[name='vftn_code']"),'短信验证码错误！');
                            return false;
                        }
                    }
                });
            };
            return false;
        });
    },
    changePicCode:function() {
        var $change = $("#changeImgCode"),
            $img = $change.prev();
        $change.on('click', function(event) {
            $img.attr('src','/image/code?random='+Math.random());
        });
    },
    /*清空$this的错误提示信息*/
    clearErrorMsg:function($this) {
        var $this = $this,
            that = this,
            typename = $this.attr('name');
        if (typename == 'phone') {
            that.flag.phone = true;
            $this.parent().next().children('.error_msg').remove();
        }else if (typename == 'psd') {
            that.flag.psd = true;
            $this.parent().next().children('.error_msg').remove();
        }else if (typename == 'cfm_psd') {
            that.flag.cfm_psd = true;
            $this.parent().next().children('.error_msg').remove();
        }else if (typename == 'vftn_code') {
            that.flag.vftn_code = true;
            $this.next().remove();
        }else if (typename == 'picode') {
            that.flag.picode = true;
            $this.parent().next().html('&nbsp;');
        };
    },
    /*显示错误信息*/
    addErrorMsg:function ($this,msg) {
        var $this = $this,
            that = this,
            typename = $this.attr('name');
        if (typename == 'phone') {
            that.flag.phone = false;
            $this.parent().next().html('<span class="error_msg">'+msg+'</span>');
        }else if (typename == 'psd') {
            that.flag.psd = false;
            $this.parent().next().html('<span class="error_msg">'+msg+'</span>');
        }else if (typename == 'cfm_psd') {
            that.flag.cfm_psd = false;
            $this.parent().next().html('<span class="error_msg">'+msg+'</span>');
        }else if (typename == 'vftn_code') {
            that.flag.vftn_code = false;
            if($this.next('.error_msg').size() != 0){
                $this.next('.error_msg').html(msg);
            }else{
                $this.after('<span class="error_msg">'+msg+'</span>');
            }
        }else if (typename == 'picode') {
            that.flag.picode = false;
            $this.parent().next().html('<span class="error_msg">'+msg+'</span>');
        };
    },
    /*显示提示信息*/
    addTipMsg:function ($this,msg) {
        var $this = $this,
            that = this,
            typename = $this.attr('name'),
            $next = $this.parent().next();
        if (typename == 'phone') {
            that.flag.email = false;
            $next.html('<span class="tip_msg">'+msg+'</span>');
            $next.children('.tip_msg').delay(2000).fadeOut(2000, function() {
               $(this).remove();
            });
        }
    }
}
$(function() {
    BSTYUN.register.init();
});

/**
 * 打开百顺通云服务协议
 */
function openDeal(){
//	window.open ('/user/openBstDeal','','height=500,width=800,top=100,left=200,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no') 
	var openUrl = "/user/openBstDeal";//弹出窗口的url
//	var iTop = (window.screen.availHeight-30-iHeight)/2; //获得窗口的垂直位置;
//	var iLeft = (window.screen.availWidth-10-iWidth)/2; //获得窗口的水平位置;
	window.open (openUrl,'_blank','width='+(window.screen.availWidth-10)+',height='+(window.screen.availHeight-30)+ 
	',top=0,left=0,toolbar=yes,menubar=yes,scrollbars=yes, resizable=yes,location=yes, status=yes,channelmode=yes');
//	 window.open(openUrl,"new","toolbar=yes,menubar=yes,scrollbars=yes, resizable=yes,location=yes, status=yes)"); 
}
